/**
 * 
 */
package com.binary.redis;


import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.util.Pool;

import com.alibaba.fastjson.JSON;

/**
 * @author c_danyanxin
 * @date 2018年7月26日
 */
public class DataRedisClient {
	
	private RedisSentinelFactory factory;
	private static  Logger logger = LoggerFactory.getLogger(DataRedisClient.class);
	
	
	public RedisSentinelFactory getFactory() {
		return factory;
	}

	public void setFactory(RedisSentinelFactory factory) {
		this.factory = factory;
	}
	public String setExpire(int index,String key,Object value,int seconds){
		String result = null;
		Pool<Jedis> pool = factory.getJedis(index);
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			if(jedis!=null){
				result = jedis.setex(key,seconds, JSON.toJSONString(value));
			}
		} catch (Exception ex) {
			result = "ERROR";
			logger.error("set 设置缓存数据 "+seconds, ex);
		}		
		return result;
	}
	public String set(int index,String key,Object value){
		String result = null;
		Pool<Jedis> pool = factory.getJedis(index);
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			if(jedis!=null){
				result = jedis.set(key, JSON.toJSONString(value));
			}
		} catch (Exception ex) {
			result = "ERROR";
			logger.error("set 设置缓存数据 永久", ex);
		}		
		return result;
	}
	
	public String get(int index,String key){
		String result = null;
		Pool<Jedis> pool = factory.getJedis(index);
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			if(jedis!=null){
				result = jedis.get(key);
			}
		} catch (Exception ex) {
			result = "ERROR";
			logger.error("get 数据 错误", ex);
		}
		return result;
	}
	
	public <T> T getJsonOneResult(int index,String key,Class<T> clas){
		T result = null;
		String res=null;
		Pool<Jedis> pool = factory.getJedis(index);
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			if(jedis!=null){
				res = jedis.get(key);
				result = JSON.parseObject(res, clas);
			}
		} catch (Exception ex) {
//			result = "ERROR";
			logger.error("get 数据 错误", ex);
		}
		return result;
	}
	public <T> List<T> getJSonResult(int index,String key,Class<T> clas){
		List<T>  list = null;
		String res = null;
		Pool<Jedis> pool = factory.getJedis(index);
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			if(jedis!=null){
				res = jedis.get(key);
				list = JSON.parseArray(res, clas);
			}
		} catch (Exception ex) {
//			result = "ERROR";
			logger.error("get 数据 错误", ex);
		}
		return list;
	}

}
